/*
 * Copyright (c) 2021 Zsj. All rights reserved.
 */

package com.jzz.crawlerweb.handler.config;

import com.jzz.crawlerweb.handler.props.CaptchaProps;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@EnableRedisHttpSession(redisNamespace = "captcha:web:session")
@Configuration
public class CaptchaWebConfig implements WebMvcConfigurer {
    private static final Logger logger = LoggerFactory.getLogger(CaptchaWebConfig.class);

    @Autowired
    private CaptchaProps captchaProps;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 初始化URL映射表
        CaptchaUrlMap.map.clear();

        // 用户可以自定义是否启动Captcha
        if (captchaProps.isEnabled() && captchaProps.getCases() != null) {
            for (CaptchaProps.Case theCase : captchaProps.getCases()) {
                if (theCase.getPaths() != null) {
                    // 仅将配置文件中的登录路径添加到拦截中
                    registry
                            .addInterceptor(new CaptchaWebInterceptor(theCase, captchaProps))
                            .addPathPatterns(theCase.getPaths());

                    for (String path : theCase.getPaths()) {
                        CaptchaUrlMap.map.put(path, theCase.getType());
                    }
                }
            }
            if (captchaProps.getLogout() != null && !captchaProps.getLogout().isEmpty()) {
                registry
                        .addInterceptor(new LogoutInterceptor(captchaProps))
                        .addPathPatterns(captchaProps.getLogout());
            }
        } else {
            logger.info("Captcha is disabled");
        }
    }
}
